using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Net.Http;
using Newtonsoft.Json;
using PddWebAuto.Model;
using PddWebAuto.Properties;

namespace PddWebAuto.ViewForm
{
    public partial class FormChromeOptions : Form
    {
        public readonly List<GroupItemModel> ItemModelList = new List<GroupItemModel>();
        private readonly bool _viewEdit;


        public FormChromeOptions(GroupItemModel m, bool IsEdit = false)
        {
            ItemModelList.Add(JsonConvert.DeserializeObject<GroupItemModel>(JsonConvert.SerializeObject(m)));
            _viewEdit = IsEdit;
            InitializeComponent();
            DialogResult = DialogResult.None;
            button1.Text = _viewEdit ? "编辑保存" : "创建浏览器";
        }

        private void FormChromeOptions_Load(object sender, EventArgs e)
        {
            Icon = Resources.a9gw7_5tcr9_001;
            if (_viewEdit)
            {
                SaveJsonOptions(ItemModelList[0], false);
                panel1.Visible = false;
            }
            else
            {
                RandomArgs(ItemModelList[0], true);
            }
        }

        /// <summary>
        ///     保存界面数据到模型
        /// </summary>
        /// <param name="m"></param>
        /// <param name="IsSave"></param>
        private void SaveJsonOptions(GroupItemModel m, bool IsSave)
        {
            var ViewsControl = new List<Control>();
            GetSupportControls(Controls, ref ViewsControl);
            var type = Type.GetType("PddWebAuto.Model.GroupItemModel");
            foreach (var ControlItem in ViewsControl)
            {
                var propertyName = ControlItem.Tag as string;
                switch (ControlItem)
                {
                    case TextBox _ when string.IsNullOrEmpty(propertyName):
                        continue;
                    case TextBox txtBox when IsSave:
                        type?.GetProperty(propertyName)?.SetValue(m, txtBox.Text);
                        break;
                    case TextBox txtBox:
                        txtBox.Text = (string)type?.GetProperty(propertyName)?.GetValue(m) ?? "";
                        break;
                    case ComboBox _ when string.IsNullOrEmpty(propertyName):
                        continue;
                    case ComboBox dropBox when IsSave:
                        type?.GetProperty(propertyName)?.SetValue(m, dropBox.Text);
                        break;
                    case ComboBox dropBox:
                        dropBox.Text = (string)type?.GetProperty(propertyName)?.GetValue(m) ?? "";
                        break;
                }
            }
        }

        private static void GetSupportControls(Control.ControlCollection controls, ref List<Control> Views)
        {
            foreach (Control cont in controls)
            {
                if (cont is TextBox || cont is ComboBox)
                {
                    Views.Add(cont);
                }

                GetSupportControls(cont.Controls, ref Views);
            }
        }

        private void FormChromeOptions_FormClosed(object sender, FormClosedEventArgs e)
        {
        }

        private async void button1_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textBox1.Text.Trim()))
            {
                MessageBox.Show(@"浏览器名称禁止为空!");
                return;
            }

            try
            {
                if (!_viewEdit)
                {
                    var Num = int.Parse(textBox6.Text);
                    if (Num == 0)
                    {
                        ItemModelList[0].ChromeData = DateTime.Now.Ticks.ToString();
                        SaveJsonOptions(ItemModelList[0], true);
                    }
                    else
                    {
                        ItemModelList.Clear();
                        for (var i = 0; i < Num; i++)
                        {
                            var m = new GroupItemModel
                            {
                                ChromeData = DateTime.Now.Ticks.ToString()
                            };
                            RandomArgs(m);
                            SaveJsonOptions(m, true);
                            m.Title = textBox1.Text.Trim();
                            m.Title = m.Title.Replace("X", (i + 1).ToString());
                            await TaskHelper.Delay(20);
                            ItemModelList.Add(m);
                        }
                    }
                }
                else
                {
                    SaveJsonOptions(ItemModelList[0], true);
                }
            }
            catch (Exception)
            {
                MessageBox.Show(@"数据处理异常!");
                return;
            }

            DialogResult = DialogResult.OK;
        }

        /// <summary>
        ///     随机参数
        /// </summary>
        /// <param name="m"></param>
        /// <param name="NotEditableOnly"></param>
        private void RandomArgs(GroupItemModel m, bool NotEditableOnly = false)
        {
            if (!NotEditableOnly)
            {
                var ViewsControl = new List<Control>();
                GetSupportControls(Controls, ref ViewsControl);
                foreach (var ControlItem in ViewsControl)
                {
                    var PropertyName = ControlItem.Tag as string;
                    switch (ControlItem)
                    {
                        case TextBox txtBox:
                        {
                            if (!string.IsNullOrEmpty(PropertyName))
                            {
                                switch (PropertyName)
                                {
                                    case "fingerprintRandom":
                                    {
                                        Thread.Sleep(5);
                                        var ran = new Random(new Random().Next(99999));
                                        txtBox.Text = ran.Next(100000, 999999).ToString();
                                        break;
                                    }
                                    case "userAgent":
                                    {
                                        Thread.Sleep(5);
                                        var ran = new Random(new Random().Next(99999));
                                        txtBox.Text =
                                            @"Mozilla/5.0 (Windows NT 6.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" +
                                            ran.Next(80, 89) + @".0." + ran.Next(1000, 3900) + @"." +
                                            ran.Next(100, 900) +
                                            @" Safari/537.36";
                                        break;
                                    }
                                    case "gpuRenderer":
                                    {
                                        Thread.Sleep(5);
                                        var ran = new Random(new Random().Next(99999));
                                        var gr = File.ReadAllLines(Path.Combine(Application.StartupPath,
                                            "GpuRenderer.txt"));
                                        if (gr.Length > 0)
                                        {
                                            txtBox.Text = gr[ran.Next(gr.Length - 1)];
                                        }

                                        break;
                                    }
                                }
                            }

                            break;
                        }
                        case ComboBox dropBox:
                        {
                            if (!string.IsNullOrEmpty(PropertyName))
                            {
                                if (dropBox.Items.Count > 0)
                                {
                                    Thread.Sleep(5);
                                    var ran = new Random(new Random().Next(99999));
                                    dropBox.SelectedIndex = ran.Next(dropBox.Items.Count - 1);
                                }
                            }

                            break;
                        }
                    }
                }
            }

            Thread.Sleep(5);
            m.macAddress = GroupItemModel.GetRandomMacAddress();

            Thread.Sleep(5);
            m.computerName = GroupItemModel.GetRandomComputerName();

            Thread.Sleep(5);
            m.userName = HttpHelper.RanMixingString(4);

            Thread.Sleep(5);
            m.speechVoices = GroupItemModel.GetRandomSpeechVoices();

            Thread.Sleep(5);
            m.position = GroupItemModel.GetRandomPosition();

            Thread.Sleep(5);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            RandomArgs(ItemModelList[0]);
        }
    }
}